//
//  MSHTTPRequest.h
//  Musou
//
//  Created by luo danal on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol  MSHTTPRequestDelegate;

@interface MSHTTPRequest : NSObject {
    NSURLConnection *_conn;
    NSMutableURLRequest *_request;
    BOOL _multipart;
    id _sender;
}

//A int mark to identify self
@property (readonly,nonatomic) NSInteger mark;
//Delegate
@property (assign,nonatomic) id<MSHTTPRequestDelegate> delegate;
//Url
@property (retain,nonatomic) NSURL *URL;
//Data received
@property (retain,nonatomic) NSMutableData *data;
//Parsed data
@property (retain,nonatomic) id result;
//Whether to parse the received data to json
@property (nonatomic) BOOL parseJson;
//Request parameters
@property (readonly, retain,nonatomic) NSMutableDictionary *requestFields;

@property (assign,nonatomic) long long expectedLength;
@property (assign,nonatomic) long long receivedLength;
@property (assign,nonatomic) float progress;
@property (assign,nonatomic) int elapsedTime;
@property (assign,nonatomic) float transferRate;
@property (readonly, retain, nonatomic) NSString *rateUnit;
@property (copy, nonatomic) void(^completionBlock)(id result, id sender);

//Set yes to make a post http request
@property (nonatomic) BOOL postMethod;

- (id)initWithDelegate:(id<MSHTTPRequestDelegate>)delegate;
//Request in asynchronism
- (int)start;
- (void)cancel;
//Request in synchronism,return NSData object,or JSON dictionary if set parseJson to YES
- (id)startSync:(NSTimeInterval)timeout;
//- (void)startSync:(NSTimeInterval)timeout completionBlock:(void (^) (id result))block;
- (void)startWithCompletion:(void (^) (id result, id sender) )block object:(id)sender;

- (void)addGetParam:(NSString *)value forField:(NSString *)field;
- (void)addUrlParamString:(NSString *)paramString;
- (void)addValue:(NSString *)value forField:(NSString *)field;

//Using when it's a post request
- (void)addPostImage:(UIImage *)image forField:(NSString *)field;
- (void)addPostFile:(NSString *)file forField:(NSString *)field;
- (void)removeField:(NSString *)field;

#pragma mark - Class methods
+ (void)setRequestTimeout:(NSTimeInterval)t;
+ (id)requestWithDelegate:(id<MSHTTPRequestDelegate>)delegate;
+ (id)requestWithUrl:(NSString *)url;
+ (id)request;

@end


@protocol MSHTTPRequestDelegate <NSObject>
@optional
- (void)requestDidStartLoading:(MSHTTPRequest *)req;
- (void)requestDidReceiveData:(MSHTTPRequest *)req data:(NSData *)data;
- (void)requestDoesTransferRateUpdate:(MSHTTPRequest *)req;
- (void)requestDoesPostProgressUpdate:(MSHTTPRequest *)req;
@required
- (void)requestDidFinishLoading:(MSHTTPRequest *)req error:(NSError *)error;
@end